package sis.report;

import sis.studentinfo.CourseSession;
import sis.studentinfo.Session;
import sis.studentinfo.Student;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2019-07-20 16:14
 * @notify 参与课程的学生
 * @version 1.0
 */

public class RosterReporter {
    public final static String ROSTER_REPORT_HEADER = "学生信息";
    public final static String ROSTER_REPORT_FOOTER = "总共";
    public final static String NEWLINE = System.getProperty("line.separator");
    private Writer writer;

    //课程类
    private Session session;

    public RosterReporter(Session session) {
        this.session = session;
    }

    public String getReport() {
        StringBuilder buffer = new StringBuilder();
        writerHeader(buffer);
        writerBody(buffer);
        writerFooter(buffer);
        return buffer.toString();
    }

    //头部
    void writerHeader(StringBuilder buffer) {
        buffer.append(ROSTER_REPORT_HEADER);
        buffer.append(NEWLINE);
    }

    void writerBody(StringBuilder buffer) {
        //该课程报名的学生
        for (Student student : session.getAllStudents()) {
            buffer.append(student.getName());
            buffer.append(NEWLINE);
        }
    }

    //底部
    void writerFooter(StringBuilder buffer) {
        buffer.append(ROSTER_REPORT_FOOTER + session.getAllStudents().size() + "个学生");
    }

    public void writeReport(Writer writer) throws IOException {
        this.writer = writer;
        writeHeader();
        writerBody();
        writerFooter();

    }
    public void writeReport(String fileName) throws IOException{
        //输出流缓冲区 装饰者模式.
        Writer bufferedWriter = new BufferedWriter(new FileWriter(fileName));
        try {
            writeReport(bufferedWriter);
        }finally {
            bufferedWriter.close();
        }
    }
    private void writeHeader() throws IOException {
        writer.write(ROSTER_REPORT_HEADER);
        writer.write(NEWLINE);
    }

    private void writerBody() throws IOException {
        //该课程报名的学生
        for (Student student : session.getAllStudents()) {
            writer.write(student.getName() + NEWLINE);
        }
    }

    private void writerFooter() throws IOException {
        writer.append(ROSTER_REPORT_FOOTER + session.getAllStudents().size() + "个学生");
    }
}
